<template>
	<view class="page-container">
		<view class="container">
			<!-- 自定义导航栏 -->
			<CustomNavbar :title="accountName + '历史记录'" />
			
			<!-- 账户信息卡片 -->
			<view class="account-info-card">
				<view class="account-header">
					<text class="account-icon">{{accountInfo.icon}}</text>
					<view class="account-details">
						<text class="account-name">{{accountInfo.name}}</text>
						<text class="account-type">{{getAccountTypeText(accountInfo.accountType)}}</text>
					</view>
				</view>
				<view class="account-balance">
					<text class="balance-label">当前余额</text>
					<text class="balance-amount">¥{{accountInfo.currentBalance || 0}}</text>
				</view>
			</view>
			
			<!-- 日期筛选 -->
			<view class="date-filter">
				<view class="filter-tabs">
					<view 
						v-for="(tab, index) in filterTabs" 
						:key="index"
						:class="['filter-tab', activeFilterIndex === index ? 'active' : '']"
						@click="selectFilter(index)"
					>
						<text class="tab-text">{{tab.name}}</text>
					</view>
				</view>
			</view>
			
			<!-- 记录列表 -->
			<view class="records-section">
				<view v-if="loading" class="loading-state">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载中...</text>
				</view>
				
				<view v-else-if="records.length > 0" class="records-list">
					<view v-for="record in records" :key="record.id" class="record-item" @click="editRecord(record)">
						<view class="record-left">
							<text class="record-icon">{{record.categoryIcon}}</text>
							<view class="record-info">
								<text class="record-category">{{record.categoryName}}</text>
								<text class="record-note">{{record.note || '无备注'}}</text>
							</view>
						</view>
						<view class="record-right">
							<text :class="['record-amount', record.recordType.toLowerCase()]">
								{{record.recordType === 'INCOME' ? '+' : '-'}}¥{{record.amount}}
							</text>
							<text class="record-date">{{formatDate(record.recordDate)}}</text>
						</view>
					</view>
				</view>
				
				<view v-else class="empty-state">
					<view class="empty-icon">📝</view>
					<text class="empty-title">暂无记录</text>
					<text class="empty-desc">该账户在此时间段内暂无交易记录</text>
				</view>
			</view>
			
			<!-- 统计信息 -->
			<view v-if="records.length > 0" class="statistics-section">
				<view class="stats-row">
					<view class="stat-item">
						<text class="stat-label">收入</text>
						<text class="stat-value income">+¥{{totalIncome}}</text>
					</view>
					<view class="stat-item">
						<text class="stat-label">支出</text>
						<text class="stat-value expense">-¥{{totalExpense}}</text>
					</view>
					<view class="stat-item">
						<text class="stat-label">净额</text>
						<text :class="['stat-value', netAmount >= 0 ? 'income' : 'expense']">
							{{netAmount >= 0 ? '+' : ''}}¥{{netAmount}}
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { accountAPI, apiUtils } from '@/utils/api.js'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				accountId: null,
				accountName: '账户',
				accountInfo: {},
				records: [],
				loading: false,
				activeFilterIndex: 0,
				filterTabs: [
					{ name: '全部', days: null },
					{ name: '本月', days: 30 },
					{ name: '近3月', days: 90 },
					{ name: '近半年', days: 180 },
					{ name: '近一年', days: 365 }
				]
			}
		},
		computed: {
			totalIncome() {
				return this.records
					.filter(record => record.recordType === 'INCOME')
					.reduce((sum, record) => sum + parseFloat(record.amount || 0), 0)
					.toFixed(2)
			},
			totalExpense() {
				return this.records
					.filter(record => record.recordType === 'EXPENSE')
					.reduce((sum, record) => sum + parseFloat(record.amount || 0), 0)
					.toFixed(2)
			},
			netAmount() {
				return (parseFloat(this.totalIncome) - parseFloat(this.totalExpense)).toFixed(2)
			}
		},
		onLoad(options) {
			// 检查登录状态
			if (!apiUtils.isLoggedIn()) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
				return;
			}
			
			if (options.accountId) {
				this.accountId = parseInt(options.accountId)
				this.accountName = options.accountName || '账户'
				this.loadAccountInfo()
				this.loadRecords()
			} else {
				uni.showToast({
					title: '账户信息错误',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		},
		onPullDownRefresh() {
			this.loadRecords()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		methods: {
			async loadAccountInfo() {
				try {
					const account = await accountAPI.getById(this.accountId)
					this.accountInfo = account
					this.accountName = account.name
				} catch (error) {
					console.error('加载账户信息失败:', error)
				}
			},
			async loadRecords() {
				try {
					this.loading = true
					console.log('加载账户历史记录，账户ID:', this.accountId, '筛选:', this.activeFilterIndex)
					
					let records = []
					const currentFilter = this.filterTabs[this.activeFilterIndex]
					
					if (currentFilter.days === null) {
						// 获取全部记录
						records = await accountAPI.getAccountRecords(this.accountId)
					} else {
						// 根据日期范围获取记录
						const endDate = new Date()
						const startDate = new Date()
						startDate.setDate(startDate.getDate() - currentFilter.days)
						
						const startDateStr = this.formatDateForAPI(startDate)
						const endDateStr = this.formatDateForAPI(endDate)
						
						records = await accountAPI.getAccountRecordsByDateRange(this.accountId, startDateStr, endDateStr)
					}
					
					this.records = records || []
					console.log('加载到的记录:', this.records)
					
				} catch (error) {
					console.error('加载历史记录失败:', error)
					uni.showToast({
						title: '加载失败: ' + error.message,
						icon: 'none'
					})
					this.records = []
				} finally {
					this.loading = false
				}
			},
			selectFilter(index) {
				this.activeFilterIndex = index
				this.loadRecords()
			},
			getAccountTypeText(type) {
				const typeMap = {
					'CASH': '现金',
					'BANK_CARD': '银行卡',
					'CREDIT_CARD': '信用卡',
					'ALIPAY': '支付宝',
					'WECHAT': '微信',
					'OTHER': '其他'
				}
				return typeMap[type] || type
			},
			formatDate(dateString) {
				const date = new Date(dateString)
				const today = new Date()
				const yesterday = new Date(today)
				yesterday.setDate(yesterday.getDate() - 1)
				
				if (date.toDateString() === today.toDateString()) {
					return '今天'
				} else if (date.toDateString() === yesterday.toDateString()) {
					return '昨天'
				} else {
					return `${date.getMonth() + 1}月${date.getDate()}日`
				}
			},
			formatDateForAPI(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			editRecord(record) {
				// 跳转到记录编辑页面
				uni.navigateTo({
					url: `/pages/add/add?edit=true&id=${record.id}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/uni.scss';
	
	.page-container {
		width: 100%;
		height: 100vh;
	}
	
	.container {
		background: $cute-gradient-bg;
		min-height: 100vh;
		padding-bottom: 120rpx;
		padding-top: calc(var(--status-bar-height, 44px) + 88rpx);
	}
	
	/* 账户信息卡片 */
	.account-info-card {
		margin: 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.account-header {
		display: flex;
		align-items: center;
	}
	
	.account-icon {
		font-size: 48rpx;
		margin-right: 20rpx;
	}
	
	.account-details {
		display: flex;
		flex-direction: column;
	}
	
	.account-name {
		font-size: 32rpx;
		font-weight: bold;
		color: $cute-text-primary;
		margin-bottom: 5rpx;
	}
	
	.account-type {
		font-size: 24rpx;
		color: $cute-text-secondary;
	}
	
	.account-balance {
		text-align: right;
	}
	
	.balance-label {
		display: block;
		font-size: 24rpx;
		color: $cute-text-secondary;
		margin-bottom: 5rpx;
	}
	
	.balance-amount {
		font-size: 32rpx;
		font-weight: bold;
		color: $cute-primary;
	}
	
	/* 日期筛选 */
	.date-filter {
		margin: 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 10rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.filter-tabs {
		display: flex;
		justify-content: space-between;
	}
	
	.filter-tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 10rpx;
		border-radius: $cute-border-radius;
		transition: $cute-transition;
		
		&.active {
			background: $cute-gradient-primary;
			
			.tab-text {
				color: $cute-text-inverse;
				font-weight: bold;
			}
		}
		
		&:active {
			transform: scale(0.95);
		}
	}
	
	.tab-text {
		font-size: 26rpx;
		color: $cute-text-primary;
	}
	
	/* 记录列表 */
	.records-section {
		margin: 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.loading-state {
		padding: 80rpx 40rpx;
		text-align: center;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid $cute-border;
		border-top-color: $cute-primary;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin: 0 auto 20rpx;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.loading-text {
		font-size: 28rpx;
		color: $cute-text-secondary;
	}
	
	.records-list {
		padding: 0 30rpx;
	}
	
	.record-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 2rpx solid $cute-divider;
		transition: $cute-transition;
		
		&:last-child {
			border-bottom: none;
		}
		
		&:active {
			background: $cute-bg-tertiary;
			margin: 0 -30rpx;
			padding: 30rpx;
			border-radius: $cute-border-radius;
		}
	}
	
	.record-left {
		display: flex;
		align-items: center;
		flex: 1;
	}
	
	.record-icon {
		font-size: 40rpx;
		margin-right: 20rpx;
	}
	
	.record-info {
		display: flex;
		flex-direction: column;
	}
	
	.record-category {
		font-size: 30rpx;
		color: $cute-text-primary;
		font-weight: 600;
		margin-bottom: 5rpx;
	}
	
	.record-note {
		font-size: 24rpx;
		color: $cute-text-secondary;
	}
	
	.record-right {
		text-align: right;
	}
	
	.record-amount {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 5rpx;
		
		&.income {
			color: #4CAF50;
		}
		
		&.expense {
			color: #F44336;
		}
	}
	
	.record-date {
		font-size: 22rpx;
		color: $cute-text-secondary;
	}
	
	/* 空状态 */
	.empty-state {
		padding: 80rpx 40rpx;
		text-align: center;
	}
	
	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-title {
		display: block;
		font-size: 32rpx;
		color: $cute-text-primary;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.empty-desc {
		font-size: 26rpx;
		color: $cute-text-secondary;
	}
	
	/* 统计信息 */
	.statistics-section {
		margin: 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.stats-row {
		display: flex;
		justify-content: space-between;
	}
	
	.stat-item {
		text-align: center;
		flex: 1;
	}
	
	.stat-label {
		display: block;
		font-size: 24rpx;
		color: $cute-text-secondary;
		margin-bottom: 10rpx;
	}
	
	.stat-value {
		font-size: 28rpx;
		font-weight: bold;
		
		&.income {
			color: #4CAF50;
		}
		
		&.expense {
			color: #F44336;
		}
	}
</style>
